<template>
  <view class="detail-page">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-left" @click="goBack">
        <u-icon name="arrow-left" color="#ffffff" size="24"></u-icon>
      </view>
      <view class="nav-center">
        <text class="nav-title">公文详情</text>
      </view>
      <view class="nav-right"> </view>
    </view>

    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 固定头部区域 -->
    <view class="fixed-header" v-else-if="documentDetail.id">
      <!-- 公文标题 -->
      <view class="title-section">
        <text class="document-title">{{ documentDetail.title || '无标题' }}</text>
        <view
          :class="[
            documentDetail.bizCategory === '党务发文' ? 'category-badge-party' : 'category-badge',
          ]"
          v-if="documentDetail.bizCategory"
        >
          <text class="badge-text">{{ documentDetail.bizCategory }}</text>
        </view>
      </view>

      <!-- 基本信息卡片 -->
      <view class="info-card">
        <view class="info-row">
          <text class="label">拟稿部门</text>
          <text class="value">{{ documentDetail.applicantDeptName || '未知' }}</text>
        </view>
        <view class="info-row">
          <text class="label">拟稿人</text>
          <text class="value">{{ documentDetail.applicantName || '未知' }}</text>
        </view>
        <view class="info-row">
          <text class="label">拟稿时间</text>
          <text class="value">{{ formatDateTime(documentDetail.createdAt) }}</text>
        </view>
      </view>

      <!-- Tab切换 -->
      <view class="tab-section">
        <view
          class="tab-item"
          :class="{ active: activeTab === 'detail' }"
          @click="switchTab('detail')"
        >
          <text class="tab-text">公文详情</text>
        </view>
        <view
          class="tab-item"
          :class="{ active: activeTab === 'attachments' }"
          @click="switchTab('attachments')"
          v-if="hasAttachments"
        >
          <text class="tab-text">附件 ({{ attachmentCount }})</text>
        </view>
        <view
          class="tab-item"
          :class="{ active: activeTab === 'redHeader' }"
          @click="switchTab('redHeader')"
          v-if="hasRedHeader"
        >
          <text class="tab-text">红头文件</text>
        </view>
        <view class="tab-item" :class="{ active: activeTab === 'flow' }" @click="switchTab('flow')">
          <text class="tab-text">流程记录</text>
        </view>
      </view>
    </view>

    <!-- 可滚动内容区域 -->
    <view class="scroll-content-wrapper" v-if="documentDetail.id">
      <!-- 公文详情内容 -->
      <view class="content-section" v-if="activeTab === 'detail'">
        <view class="detail-content">
          <!-- 收发信息 -->
          <view
            class="section-block"
            v-if="documentDetail.mainRecipient || documentDetail.ccRecipient"
          >
            <view class="block-header">
              <text class="block-title">收发信息</text>
            </view>
            <view class="block-content">
              <view class="detail-row" v-if="documentDetail.mainRecipient">
                <text class="row-label">主送：</text>
                <text class="row-value">{{ documentDetail.mainRecipient }}</text>
              </view>
              <view class="detail-row" v-if="documentDetail.ccRecipient">
                <text class="row-label">抄送：</text>
                <text class="row-value">{{ documentDetail.ccRecipient }}</text>
              </view>
            </view>
          </view>

          <!-- 发文信息 -->
          <view class="section-block">
            <view class="block-header">
              <text class="block-title">发文信息</text>
            </view>
            <view class="block-content">
              <view class="detail-row" v-if="documentDetail.issueYear || documentDetail.issueHao">
                <text class="row-label">发文字号：</text>
                <text class="row-value">
                  {{ documentDetail.issueNumber }}〔{{ documentDetail.issueYear }}〕{{
                    documentDetail.issueHao
                  }}号
                </text>
              </view>
              <view
                class="detail-row"
                v-if="documentDetail.disclosureMethod && documentDetail.bizCategory === '行政发文'"
              >
                <text class="row-label">公开方式：</text>
                <text class="row-value">{{ documentDetail.disclosureMethod }}</text>
              </view>
              <view
                class="detail-row"
                v-if="
                  documentDetail.involvesEconomicActivity &&
                  documentDetail.bizCategory === '行政发文'
                "
              >
                <text class="row-label">涉及经济活动：</text>
                <text class="row-value">{{ documentDetail.involvesEconomicActivity }}</text>
              </view>
              <view
                class="detail-row"
                v-if="
                  documentDetail.needCompetitionReview && documentDetail.bizCategory === '行政发文'
                "
              >
                <text class="row-label">需要公平竞争审查：</text>
                <text class="row-value">{{ documentDetail.needCompetitionReview }}</text>
              </view>
              <view class="detail-row" v-if="documentDetail.proofreader">
                <text class="row-label">校对人：</text>
                <text class="row-value">{{ documentDetail.proofreader }}</text>
              </view>
              <view class="detail-row" v-if="documentDetail.sealAndDispatch">
                <text class="row-label">签发人：</text>
                <text class="row-value">{{ documentDetail.sealAndDispatch }}</text>
              </view>
              <view class="detail-row" v-if="documentDetail.totalcopies">
                <text class="row-label">印发份数：</text>
                <text class="row-value">{{ documentDetail.totalcopies }}</text>
              </view>
            </view>
          </view>

          <!-- 签批信息 -->
          <view class="section-block" v-if="hasApprovalSummary">
            <view class="block-header">
              <text class="block-title">签批信息</text>
            </view>
            <view class="block-content">
              <view
                class="detail-row multi-line-row"
                v-if="
                  approvalSummary.departmentReview.userName ||
                  approvalSummary.departmentReview.content
                "
              >
                <text class="row-label">部门负责人审稿：</text>
                <view class="row-value column">
                  <text
                    v-for="(line, index) in getSummaryLines(approvalSummary.departmentReview)"
                    :key="`department-${index}`"
                    class="row-line"
                  >
                    {{ line }}
                  </text>
                </view>
              </view>

              <view
                class="detail-row multi-line-row"
                v-if="approvalSummary.officeReview.userName || approvalSummary.officeReview.content"
              >
                <text class="row-label">办公室审核：</text>
                <view class="row-value column">
                  <text
                    v-for="(line, index) in getSummaryLines(approvalSummary.officeReview)"
                    :key="`office-${index}`"
                    class="row-line"
                  >
                    {{ line }}
                  </text>
                </view>
              </view>

              <view
                class="detail-row multi-line-row"
                v-if="approvalSummary.deputyReview.userName || approvalSummary.deputyReview.content"
              >
                <text class="row-label">核稿：</text>
                <view class="row-value column">
                  <text
                    v-for="(line, index) in getSummaryLines(approvalSummary.deputyReview)"
                    :key="`deputy-${index}`"
                    class="row-line"
                  >
                    {{ line }}
                  </text>
                </view>
              </view>

              <view class="detail-row multi-line-row" v-if="approvalSummary.signer.userName">
                <text class="row-label">签发：</text>
                <view class="row-value column">
                  <text
                    v-for="(line, index) in getSummaryLines(approvalSummary.signer)"
                    :key="`signer-${index}`"
                    class="row-line"
                  >
                    {{ line }}
                  </text>
                </view>
              </view>

              <view
                class="detail-row multi-line-row"
                v-if="approvalSummary.proofreader.userName || approvalSummary.proofreader.content"
              >
                <text class="row-label">校对：</text>
                <view class="row-value column">
                  <text
                    v-for="(line, index) in getSummaryLines(approvalSummary.proofreader)"
                    :key="`proofreader-${index}`"
                    class="row-line"
                  >
                    {{ line }}
                  </text>
                </view>
              </view>

              <view class="detail-row multi-line-row" v-if="approvalSummary.sealDate">
                <text class="row-label">封发日期：</text>
                <view class="row-value column">
                  <text class="row-line">
                    {{ formatDateTime(approvalSummary.sealDate) }}
                  </text>
                </view>
              </view>
            </view>
          </view>

          <!-- 公文内容 -->
          <view class="section-block" v-if="documentDetail.content">
            <view class="block-header">
              <text class="block-title">公文内容</text>
            </view>
            <view class="block-content">
              <text class="content-text">{{ documentDetail.content }}</text>
            </view>
          </view>

          <!-- 正文 -->
          <view class="section-block" v-if="documentDetail.draftFilePath">
            <view class="block-header word-content">
              <text class="block-title">word正文</text>
              <view class="file-actions-row">
                <view class="action-btn preview" @click="previewFile(documentDetail.draftFilePath)">
                  <u-icon name="eye" color="#ffffff" size="18"></u-icon>
                  <text class="btn-text">预览</text>
                </view>
                <!-- <view
                  class="action-btn download"
                  @click="downloadFile(documentDetail.draftFilePath)"
                >
                  <u-icon name="download" color="#ffffff" size="18"></u-icon>
                  <text class="btn-text">下载</text>
                </view> -->
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 附件列表 -->
      <view class="content-section" v-if="activeTab === 'attachments'">
        <view class="attachments-list" v-if="attachmentList.length > 0">
          <view class="attachment-item" v-for="attachment in attachmentList" :key="attachment.id">
            <view class="file-info">
              <view class="file-details">
                <text class="file-name">{{ showFileName(attachment.fileName) }}</text>
                <view class="file-meta">
                  <text class="file-size">{{ formatFileSize(attachment.fileSize) }}</text>
                  <text class="file-uploader" v-if="attachment.uploadUserName">
                    上传人：{{ attachment.uploadUserName }}
                  </text>
                </view>
              </view>
            </view>
            <view class="file-actions">
              <u-icon
                name="eye"
                color="#1890ff"
                size="24"
                v-if="canPreview(attachment.fileName)"
                @click="previewAttachmentFile(attachment)"
              ></u-icon>
              <u-icon
                name="download"
                color="#1890ff"
                size="24"
                @click="downloadAttachmentFile(attachment)"
              ></u-icon>
            </view>
          </view>
        </view>
        <view class="empty-attachments" v-else>
          <text class="empty-icon">📎</text>
          <text class="empty-text">暂无附件</text>
        </view>
      </view>

      <!-- 红头文件 -->
      <view class="content-section" v-if="activeTab === 'redHeader'">
        <view class="red-header-section">
          <!-- PDF预览提示 -->
          <view class="preview-tip">
            <text class="tip-icon">📄</text>
            <text class="tip-text">红头文件预览</text>
          </view>

          <!-- 操作按钮 -->
          <view class="red-header-actions">
            <view class="action-btn-red preview" @click="previewRedHeader">
              <u-icon name="eye" color="#ffffff " size="24"></u-icon>
              <text class="btn-text">预览红头文件</text>
            </view>
            <view class="action-btn-red download" @click="downloadRedHeader">
              <u-icon name="download" color="#1890ff" size="24"></u-icon>
              <text class="btn-text">下载红头文件</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 流程记录 -->
      <view class="content-section" v-if="activeTab === 'flow'">
        <view class="flow-records" v-if="flowRecords.length > 0">
          <view class="record-item" v-for="(record, index) in flowRecords" :key="record.id">
            <view class="record-timeline">
              <view class="timeline-dot" :class="getRecordStatusClass(record)"></view>
              <view
                class="timeline-line"
                v-if="index < flowRecords.length - 1 || internalReceiveRecords.length > 0"
              ></view>
            </view>
            <view class="record-content">
              <view class="record-header">
                <text class="step-name">{{
                  record.stepName || record.approverRole || '未知步骤'
                }}</text>
                <view class="status-badge" :class="getRecordStatusClass(record)">
                  <text class="status-text">{{ getApprovalResultText(record) }}</text>
                </view>
              </view>
              <view class="record-info">
                <text class="info-text">审批人：{{ record.approverName || '未知' }}</text>
              </view>
              <view class="record-opinion" v-if="record.approvedAt">
                <text class="opinion-label">审批意见：</text>

                <!-- 优先显示签名，带白底 -->
                <view
                  v-if="record.signature"
                  class="signature-box"
                  @click.stop="previewImage(record.signature)"
                >
                  <image
                    :src="record.signature"
                    mode="heightFix"
                    style="height: 80rpx; display: block"
                  />
                </view>

                <!-- 没签名显示文字，允许为空 -->
                <text class="opinion-text" v-else>
                  {{
                    record.approvalComment && record.approvalComment !== '-'
                      ? record.approvalComment
                      : ''
                  }}
                </text>
              </view>
              <view class="record-time">
                <text class="time-text">{{
                  formatDateTime(record.approvedAt || record.createdAt)
                }}</text>
              </view>
            </view>
          </view>

          <!-- 内部分发查看记录分隔标识 -->
          <view class="distribution-divider" v-if="internalReceiveRecords.length > 0">
            <view class="divider-line"></view>
            <view class="divider-label">
              <text class="divider-text">内部分发查看记录</text>
              <view class="divider-badge">{{ internalReceiveRecords.length }}</view>
            </view>
            <view class="divider-line"></view>
          </view>

          <!-- 内部分发查看记录 -->
          <view
            class="record-item"
            v-for="(record, index) in internalReceiveRecords"
            :key="record.id"
          >
            <view class="record-timeline">
              <view
                class="timeline-dot"
                :class="record.isRead === 1 ? 'approved' : 'pending'"
              ></view>
              <view class="timeline-line" v-if="index < internalReceiveRecords.length - 1"></view>
            </view>
            <view class="record-content">
              <view class="record-header">
                <text class="step-name">{{ record.receiveDeptName || '未知部门' }}</text>
                <view class="status-badge" :class="record.isRead === 1 ? 'approved' : 'pending'">
                  <text class="status-text">{{ record.isRead === 1 ? '已阅读' : '未阅读' }}</text>
                </view>
              </view>
              <view class="record-info">
                <text class="info-text">负责人：{{ record.receiveUserName || '未知' }}</text>
                <text class="info-text">分发时间：{{ formatDateTime(record.createdAt) }}</text>
              </view>
              <view class="record-time" v-if="record.isRead === 1">
                <text class="time-text">阅读时间：{{ formatDateTime(record.readAt) }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="empty-flow" v-else>
          <text class="empty-icon">📋</text>
          <text class="empty-text">暂无流程记录</text>
        </view>
      </view>
    </view>

    <!-- 错误状态 -->
    <view class="error-state" v-else>
      <text class="error-icon">❌</text>
      <text class="error-text">加载公文详情失败</text>
      <text class="error-btn" @click="loadDocumentDetail">重新加载</text>
    </view>

    <!-- 底部操作栏 -->
    <!-- 审批操作 -->
    <view class="bottom-actions" v-if="showApprovalActions && documentDetail.id">
      <view class="action-btn reject" @click="handleReject">
        <text class="btn-text">拒绝</text>
      </view>
      <view class="action-btn approve" @click="handleApprove">
        <text class="btn-text">同意</text>
      </view>
    </view>

    <!-- 套红操作 -->
    <view class="bottom-actions single-action" v-if="showRedHeaderAction && documentDetail.id">
      <view class="action-btn primary" @click="handleRedHeaderAction">
        <text class="btn-text">套红</text>
      </view>
    </view>

    <!-- 签章操作 -->
    <view class="bottom-actions single-action" v-if="showSealAction && documentDetail.id">
      <view class="action-btn primary" @click="handleSealAction">
        <text class="btn-text">签章</text>
      </view>
    </view>

    <!-- 分发操作 -->
    <view class="bottom-actions single-action" v-if="showDistributeAction && documentDetail.id">
      <view class="action-btn primary" @click="handleDistributeAction">
        <text class="btn-text">分发</text>
      </view>
    </view>
  </view>

  <!-- 审批弹窗 -->
  <view class="approval-modal" v-if="showApprovalModal" @click="closeApprovalModal">
    <view class="modal-content" @click.stop>
      <view class="modal-header">
        <text class="modal-title">公文审批</text>
        <text class="close-btn" @click="closeApprovalModal">✕</text>
      </view>

      <view class="modal-body">
        <!-- 审批操作选择 -->
        <view class="approval-actions">
          <view
            class="action-option"
            :class="{ active: approvalForm.action === 'approve' }"
            @click="selectAction('approve')"
          >
            <u-icon
              name="checkmark"
              :color="approvalForm.action === 'approve' ? '#ffffff' : '#333333'"
              size="24"
            ></u-icon>
            <text class="option-text">同意</text>
          </view>
          <view
            class="action-option"
            :class="{ active: approvalForm.action === 'reject' }"
            @click="selectAction('reject')"
          >
            <u-icon
              name="close"
              :color="approvalForm.action === 'reject' ? '#ffffff' : '#333333'"
              size="24"
            ></u-icon>
            <text class="option-text">拒绝</text>
          </view>
        </view>

        <!-- 审批意见 -->
        <view class="opinion-section">
          <view
            class="section-header"
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 16rpx;
            "
          >
            <text class="section-label" style="margin-bottom: 0">审批意见</text>
            <view
              class="action-btn"
              @click="openSignaturePad"
              style="font-size: 24rpx; color: #1890ff; display: flex; align-items: center"
            >
              <u-icon name="edit-pen" size="28" color="#1890ff"></u-icon>
              <text style="margin-left: 4rpx">手写意见</text>
            </view>
          </view>

          <view
            v-if="signaturePath"
            class="signature-preview"
            style="
              margin-bottom: 16rpx;
              position: relative;
              background: #f9f9f9;
              padding: 10rpx;
              border-radius: 8rpx;
            "
          >
            <image
              :src="signaturePath"
              mode="heightFix"
              style="height: 120rpx; min-width: 200rpx"
            />
            <view
              class="close-icon"
              @click.stop="signaturePath = ''"
              style="
                position: absolute;
                top: -10rpx;
                right: -10rpx;
                background: #fff;
                border-radius: 50%;
                box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
                padding: 4rpx;
              "
            >
              <u-icon name="close-circle-fill" size="32" color="#999"></u-icon>
            </view>
          </view>

          <textarea
            v-if="!signaturePath"
            v-model="approvalForm.opinion"
            class="opinion-textarea"
            placeholder="请输入审批意见"
            maxlength="500"
          />
          <text v-if="!signaturePath" class="char-count"
            >{{ approvalForm.opinion.length }}/500</text
          >
        </view>

        <!-- 当前步骤信息 -->
        <view class="step-info" v-if="documentDetail.currentStepName">
          <text class="info-label">当前步骤：</text>
          <text class="info-value">{{ documentDetail.currentStepName }}</text>
        </view>
      </view>

      <view class="modal-footer">
        <view class="footer-btn cancel" @click="closeApprovalModal">
          <text class="btn-text">取消</text>
        </view>
        <view class="footer-btn confirm" @click="submitApproval" :class="{ disabled: !canSubmit }">
          <text class="btn-text">确定</text>
        </view>
      </view>
    </view>
  </view>

  <!-- 选择审批人员弹窗 -->
  <view class="approver-modal" v-if="showApproverSelectModal" @click="closeApproverSelectModal">
    <view class="modal-content-large" @click.stop>
      <view class="modal-header">
        <text class="modal-title">选择 {{ nextStepName }}</text>
        <text class="close-btn" @click="closeApproverSelectModal">✕</text>
      </view>

      <view class="modal-body-scroll">
        <!-- 说明 -->
        <view class="approval-tip">
          <text class="tip-icon">ℹ️</text>
          <view class="tip-content">
            <text class="tip-text" v-if="availableApprovers.length === 1"
              >单人审批：系统已自动选择审批人员</text
            >
            <text class="tip-text" v-else>多人审批：请选择审批人员，选择顺序即为审批顺序</text>
          </view>
        </view>

        <!-- 单人审批：显示已选人员 -->
        <view class="single-approver" v-if="availableApprovers.length === 1">
          <view class="approver-card auto-selected">
            <view class="approver-info">
              <text class="approver-name">{{ availableApprovers[0].name }}</text>
              <text class="approver-dept">{{ availableApprovers[0].deptName }}</text>
            </view>
            <view class="auto-tag">
              <text class="tag-text">已自动选择</text>
            </view>
          </view>
        </view>

        <!-- 多人审批：选择列表 -->
        <view class="multi-approver" v-else>
          <!-- 可选审批人员 -->
          <view class="approver-section">
            <text class="section-title">可选审批人员 ({{ availableApprovers.length }})</text>
            <view class="approver-list">
              <view
                class="approver-item"
                v-for="approver in availableApprovers"
                :key="approver.id"
                :class="{ selected: selectedApprovers.includes(approver.id) }"
                @click="selectApprover(approver.id)"
              >
                <view class="approver-info">
                  <text class="approver-name">{{ approver.name }}</text>
                  <text class="approver-dept">{{ approver.deptName }}</text>
                </view>
                <text class="check-icon" v-if="selectedApprovers.includes(approver.id)">✓</text>
              </view>
            </view>
          </view>

          <!-- 已选审批人员 -->
          <view class="selected-section" v-if="selectedApprovers.length > 0">
            <text class="section-title">已选审批人员 ({{ selectedApprovers.length }})</text>
            <view class="selected-list">
              <view
                class="selected-item"
                v-for="(approverId, index) in selectedApprovers"
                :key="approverId"
              >
                <text class="order-number">{{ index + 1 }}</text>
                <view class="approver-info">
                  <text class="approver-name">{{
                    getApproverById(approverId)?.name || '未知'
                  }}</text>
                  <text class="approver-dept">{{
                    getApproverById(approverId)?.deptName || '未分配部门'
                  }}</text>
                </view>
                <text class="remove-icon" @click.stop="removeApprover(approverId)">✕</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 审批意见 -->
        <view class="opinion-section">
          <view
            class="section-header"
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 16rpx;
            "
          >
            <text class="section-label" style="margin-bottom: 0">审批意见</text>
            <view
              class="action-btn"
              @click="openSignaturePad"
              style="font-size: 24rpx; color: #1890ff; display: flex; align-items: center"
            >
              <u-icon name="edit-pen" size="28" color="#1890ff"></u-icon>
              <text style="margin-left: 4rpx">手写意见</text>
            </view>
          </view>

          <view
            v-if="signaturePath"
            class="signature-preview"
            style="
              margin-bottom: 16rpx;
              position: relative;
              background: #f9f9f9;
              padding: 10rpx;
              border-radius: 8rpx;
            "
          >
            <image
              :src="signaturePath"
              mode="heightFix"
              style="height: 120rpx; min-width: 200rpx"
            />
            <view
              class="close-icon"
              @click.stop="signaturePath = ''"
              style="
                position: absolute;
                top: -10rpx;
                right: -10rpx;
                background: #fff;
                border-radius: 50%;
                box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
                padding: 4rpx;
              "
            >
              <u-icon name="close-circle-fill" size="32" color="#999"></u-icon>
            </view>
          </view>

          <textarea
            v-model="approvalForm.opinion"
            class="opinion-textarea"
            placeholder="请输入审批意见"
            maxlength="500"
          />
          <text class="char-count">{{ approvalForm.opinion.length }}/500</text>
        </view>
      </view>

      <view class="modal-footer">
        <view class="footer-btn cancel" @click="closeApproverSelectModal">
          <text class="btn-text">取消</text>
        </view>
        <view
          class="footer-btn confirm"
          @click="submitApprovalWithApprovers"
          :class="{ disabled: !canSubmitWithApprovers }"
        >
          <text class="btn-text">确认提交</text>
        </view>
      </view>
    </view>
  </view>

  <!-- 印章选择器 -->
  <SealSelector
    :visible="sealSelectorVisible"
    @update:visible="sealSelectorVisible = $event"
    @confirm="handleSealConfirm"
  />

  <!-- 分发选择器 -->
  <DistributeSelector
    :visible="distributeSelectorVisible"
    @update:visible="distributeSelectorVisible = $event"
    @confirm="handleDistributeConfirm"
  />

  <!-- 签名板弹窗 -->
  <u-popup
    :show="showSignaturePad"
    mode="center"
    :round="0"
    :overlay="false"
    :customStyle="{ width: '100vw', height: '100vh', margin: 0 }"
  >
    <view class="signature-popup-container">
      <view class="popup-header">
        <text class="title">手写意见</text>
        <u-icon name="close" size="40" color="#999" @click="closeSignaturePad"></u-icon>
      </view>

      <view class="signature-content">
        <l-signature
          ref="signatureRef"
          :landscape="true"
          @confirm="handleSignatureConfirm"
        ></l-signature>
      </view>

      <view class="popup-footer">
        <view class="btn reset" @click="handleSignatureReset">
          <u-icon name="reload" size="32" color="#666"></u-icon>
          <text>重写</text>
        </view>
        <view class="btn confirm" @click="saveSignature">
          <u-icon name="checkmark" size="32" color="#ffffff"></u-icon>
          <text>确认使用</text>
        </view>
      </view>
    </view>
  </u-popup>

  <!-- 图片预览弹窗 -->
  <u-popup :show="showImageModal" mode="center" :round="10" @close="showImageModal = false">
    <view
      style="
        width: 650rpx;
        background: #fff;
        border-radius: 20rpx;
        overflow: hidden;
        position: relative;
      "
    >
      <view
        style="
          padding: 30rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 300rpx;
          background: #fff;
        "
      >
        <image :src="previewImageUrl" mode="widthFix" style="width: 100%; display: block" />
      </view>
      <view
        @click="showImageModal = false"
        style="
          position: absolute;
          top: 20rpx;
          right: 20rpx;
          z-index: 100;
          background: rgba(0, 0, 0, 0.1);
          border-radius: 50%;
          padding: 10rpx;
        "
      >
        <u-icon name="close" size="30" color="#333"></u-icon>
      </view>
    </view>
  </u-popup>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import {
  getDocumentDetail,
  submitDocumentApproval,
  getApprovalFlowRecords,
  getApproversByStep,
  submitDocumentWithApprovers,
  jumpAddRedStamp,
  applyRedHeader,
  applySeal,
  distributeDocument,
  getInternalDocumentDistributions,
  getDocumentAttachments,
  downloadAttachment,
  type DocumentItem,
  type SealInfo,
  type AttachmentInfo,
} from '@/Api/document'
import { uploadFile } from '@/Api/request'
import { UserManager } from '@/utils/user'
import SealSelector from '@/components/SealSelector.vue'
import DistributeSelector from '@/components/DistributeSelector.vue'

// 页面参数
const documentId = ref<number>(0)
// 来源：todo-待审批, view-仅查看, redHeader-待套红, seal-待签章, distribute-待分发
const source = ref<string>('')

// 加载状态
const loading = ref(false)
const isSubmitting = ref(false) // 提交中状态，防止重复点击

// 当前Tab
const activeTab = ref<'detail' | 'flow' | 'attachments' | 'redHeader'>('detail')

// 公文详情
const documentDetail = ref<any>({})

// 流程记录
const flowRecords = ref<any[]>([])

// 内部分发查看记录
const internalReceiveRecords = ref<any[]>([])

// 附件列表（从API获取的真实附件数据）
const attachmentList = ref<AttachmentInfo[]>([])

// 流程记录是否已加载
const flowRecordsLoaded = ref(false)

// 审批摘要信息
const approvalSummary = reactive({
  departmentReview: {
    userName: '',
    date: '',
    content: '',
  },
  officeReview: {
    userName: '',
    date: '',
    content: '',
  },
  deputyReview: {
    userName: '',
    date: '',
    content: '',
  },
  signer: {
    userName: '',
    date: '',
    content: '',
  },
  proofreader: {
    userName: '',
    date: '',
    content: '',
  },
  sealDate: '',
})

const hasApprovalSummary = computed(() => {
  return (
    !!approvalSummary.departmentReview.userName ||
    !!approvalSummary.departmentReview.content ||
    !!approvalSummary.officeReview.userName ||
    !!approvalSummary.officeReview.content ||
    !!approvalSummary.deputyReview.userName ||
    !!approvalSummary.deputyReview.content ||
    !!approvalSummary.signer.userName ||
    !!approvalSummary.signer.content ||
    !!approvalSummary.proofreader.userName ||
    !!approvalSummary.sealDate
  )
})

// 是否有附件
const hasAttachments = computed(() => {
  return attachmentList.value && attachmentList.value.length > 0
})

// 附件数量
const attachmentCount = computed(() => {
  return attachmentList.value?.length || 0
})

// 获取附件列表（兼容旧的attachmentPaths字段）
const getAttachments = computed(() => {
  return attachmentList.value
})

// 是否有红头文件
const hasRedHeader = computed(() => {
  return !!documentDetail.value.redHeaderFilePdf || !!documentDetail.value.redHeaderFilePath
})

// 是否显示审批操作
const showApprovalActions = computed(() => {
  return source.value === 'todo' || source.value === 'approval'
})

// 是否显示套红操作
const showRedHeaderAction = computed(() => {
  return source.value === 'redHeader'
})

// 是否显示签章操作
const showSealAction = computed(() => {
  return source.value === 'seal'
})

// 是否显示分发操作
const showDistributeAction = computed(() => {
  console.log('[showDistributeAction] 检查是否显示分发按钮:', {
    source: source.value,
    documentId: documentDetail.value?.id,
    isDistributed: documentDetail.value?.isDistributed,
    completedAt: documentDetail.value?.completedAt,
    status: documentDetail.value?.status,
  })

  // 1. 如果是从待分发列表进入，直接显示
  if (source.value === 'distribute') {
    console.log('[showDistributeAction] ✅ 从待分发列表进入，显示分发按钮')
    return true
  }

  // 2. 判断公文是否符合分发条件：
  // - 未分发（isDistributed = 0 或 undefined）
  // - 流程已完成（completedAt 有值，或者 status 为完成状态）
  if (!documentDetail.value || !documentDetail.value.id) {
    console.log('[showDistributeAction] ❌ 公文数据无效')
    return false
  }

  const isNotDistributed =
    documentDetail.value.isDistributed === 0 || documentDetail.value.isDistributed === undefined
  const isCompleted =
    !!documentDetail.value.completedAt ||
    documentDetail.value.status === 'completed' ||
    documentDetail.value.status === '已完成'

  console.log('[showDistributeAction] 条件判断:', {
    isNotDistributed,
    isCompleted,
    result: isNotDistributed && isCompleted,
  })

  if (isNotDistributed && isCompleted) {
    console.log('[showDistributeAction] ✅ 公文已完成且未分发，显示分发按钮')
    return true
  }

  console.log('[showDistributeAction] ❌ 不满足分发条件，不显示按钮')
  return false
})

// 审批弹窗显示状态
const showApprovalModal = ref(false)

// 选择审批人员弹窗显示状态
const showApproverSelectModal = ref(false)

// 印章选择器显示状态
const sealSelectorVisible = ref(false)

// 当前选中的印章
const selectedSeal = ref<SealInfo | null>(null)

// 分发选择器显示状态
const distributeSelectorVisible = ref(false)

// 图片预览相关
const showImageModal = ref(false)
const previewImageUrl = ref('')

// 签名相关
const signaturePath = ref('')
const showSignaturePad = ref(false)
const signatureRef = ref(null)

// 打开签名板
const openSignaturePad = () => {
  showSignaturePad.value = true
}

// 关闭签名板
const closeSignaturePad = () => {
  showSignaturePad.value = false
}

// 重写签名
const handleSignatureReset = () => {
  signatureRef.value?.clear()
}

// 保存签名（点击确认使用按钮）
const saveSignature = () => {
  if (signatureRef.value) {
    signatureRef.value.canvasToTempFilePath({
      success: (res: any) => {
        if (res.isEmpty) {
          uni.showToast({ title: '请先签名', icon: 'none' })
          return
        }
        // 调用上传逻辑
        handleSignatureConfirm(res)
      },
      fail: (err: any) => {
        console.error('生成图片失败:', err)
        uni.showToast({ title: '生成图片失败', icon: 'none' })
      },
    })
  }
}

// 确认签名（上传逻辑）
const handleSignatureConfirm = async (res: any) => {
  const tempFilePath = res.tempFilePath || res

  if (!tempFilePath) {
    uni.showToast({ title: '请先签名', icon: 'none' })
    return
  }

  try {
    uni.showLoading({ title: '正在上传签名...' })

    const response = await uploadFile({
      url: '/system/file/upload',
      filePath: tempFilePath,
      name: 'file',
    })

    uni.hideLoading()

    if (response.code === 200 && response.data) {
      signaturePath.value = response.data.url
      showSignaturePad.value = false

      // 如果有签名，清空文字意见
      approvalForm.value.opinion = ''

      uni.showToast({ title: '签名已保存', icon: 'success' })
    } else {
      uni.showToast({ title: response.message || '签名上传失败', icon: 'none' })
    }
  } catch (error: any) {
    uni.hideLoading()
    console.error('签名上传失败:', error)
    uni.showToast({ title: error.message || '签名上传失败', icon: 'none' })
  }
}

// 审批表单
const approvalForm = ref({
  action: '', // 'approve' | 'reject'
  opinion: '', // 审批意见
})

// 审批人员相关
const availableApprovers = ref<any[]>([]) // 可选审批人员列表
const selectedApprovers = ref<number[]>([]) // 已选审批人员ID列表
const nextStepName = ref('') // 下一步骤名称

// 是否可以提交普通审批
const canSubmit = computed(() => {
  // 必须选择审批动作
  if (!approvalForm.value.action) return false

  // 如果有签名，意见可以为空
  if (signaturePath.value) return true

  // 如果没有签名，意见必须非空
  return approvalForm.value.opinion.trim().length >= 1
})

// 是否可以提交选人审批
const canSubmitWithApprovers = computed(() => {
  // 必须选择审批人员
  if (selectedApprovers.value.length === 0) return false

  // 如果有签名，意见可以为空
  if (signaturePath.value) return true

  // 如果没有签名，意见必须非空
  return approvalForm.value.opinion.trim().length >= 1
})

// 获取当前用户ID
const getCurrentUserId = () => {
  try {
    const userInfo = UserManager.getCurrentUser()
    return userInfo?.id || 0
  } catch (error) {
    console.error('[getCurrentUserId] 获取用户ID失败:', error)
    return 0
  }
}

// 加载可选审批人员
const loadAvailableApprovers = async (documentId: number, stepOrder: number) => {
  try {
    const response = await getApproversByStep(documentId, stepOrder)

    // 兼容不同的响应结构
    let actualData = null
    if (response.data && response.data.code === 200) {
      actualData = response.data.data
    } else if (response.code === 200) {
      // 有些接口直接返回在response.data，没有二次包装
      actualData = response.data
    }

    console.log('[loadAvailableApprovers] 解析后的actualData:', actualData)

    if (actualData && Array.isArray(actualData)) {
      availableApprovers.value = actualData.map((user: any) => ({
        id: user.id,
        name: user.realName || user.nickname || user.username,
        deptName: user.deptName || '未分配部门',
        job: user.job || '领导',
      }))
      console.log('[loadAvailableApprovers] 成功解析审批人员:', availableApprovers.value)
    } else {
      console.warn('[loadAvailableApprovers] 未获取到有效的审批人员数据')
      availableApprovers.value = []
    }
  } catch (error) {
    console.error('[loadAvailableApprovers] 加载审批人员失败:', error)
    availableApprovers.value = []
    throw error
  }
}

// 选择审批人员
const selectApprover = (approverId: number) => {
  if (!selectedApprovers.value.includes(approverId)) {
    selectedApprovers.value.push(approverId)
  }
}

// 删除审批人员
const removeApprover = (approverId: number) => {
  const index = selectedApprovers.value.indexOf(approverId)
  if (index > -1) {
    selectedApprovers.value.splice(index, 1)
  }
}

// 根据ID获取审批人员信息
const getApproverById = (approverId: number) => {
  return availableApprovers.value.find((approver) => approver.id === approverId)
}

// 格式化日期时间
const formatDateTime = (dateTime?: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}/${month}/${day}`
}

// 获取紧急程度样式
const getUrgencyClass = (level: string) => {
  const classMap: any = {
    特急: 'urgent',
    急件: 'high',
    平件: 'normal',
  }
  return classMap[level] || 'normal'
}

// 获取审批结果文本（参考网页端逻辑，只看 approvedAt）
const getApprovalResultText = (record: any) => {
  console.log('[getApprovalResultText] 处理记录:', {
    approvedAt: record.approvedAt,
    status: record.status,
  })

  // 核心逻辑：只要有 approvedAt 就是已完成，与网页端保持一致
  if (!record.approvedAt) {
    return '进行中'
  }

  // 有 approvedAt 时，优先根据 status 判断具体结果
  const status = (record.status || '').toLowerCase()

  if (status === 'reject' || status === 'rejected') {
    return '已拒绝'
  } else if (status === 'returned') {
    return '已退回'
  } else {
    // 其他情况（包括 approved、pending 等）都显示已完成
    return '已完成'
  }
}

// 获取审批记录状态样式（参考网页端逻辑，只看 approvedAt）
const getRecordStatusClass = (record: any) => {
  console.log('[getRecordStatusClass] 处理记录:', {
    approvedAt: record.approvedAt,
    status: record.status,
  })

  // 核心逻辑：只要有 approvedAt 就是已完成，与网页端保持一致
  if (!record.approvedAt) {
    return 'pending' // 进行中 - 黄色
  }

  // 有 approvedAt 时，只看 status 是否明确为拒绝或退回
  const status = (record.status || '').toLowerCase()

  if (status === 'reject' || status === 'rejected') {
    return 'rejected' // 已拒绝 - 红色
  } else if (status === 'returned') {
    return 'returned' // 已退回 - 灰色
  } else {
    // 其他所有情况（approved、pending 或空）都显示为已完成 - 绿色
    return 'approved'
  }
}

// 获取文件名
const getFileName = (filePath: string) => {
  if (!filePath) return '未知文件'
  const parts = filePath.split('/')
  return parts[parts.length - 1]
}

const extractApprovalComment = (record: any) =>
  record?.approvalComment ?? record?.approvalComent ?? record?.comment ?? ''

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (!size) return '0 B'
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
  if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(1) + ' MB'
  return (size / (1024 * 1024 * 1024)).toFixed(1) + ' GB'
}

const isRejectedStatus = (status?: string) => {
  if (!status) return false
  const normalized = status.toLowerCase()
  return normalized === 'rejected' || normalized === 'reject'
}

const buildNameWithDate = (name?: string, date?: string) => {
  const parts: string[] = []
  if (name) parts.push(name)
  if (date) parts.push(formatDateTime(date))
  return parts.join(' ')
}

const getSummaryLines = (section: { content?: string; userName?: string; date?: string }) => {
  const lines: string[] = []
  if (section?.content) {
    lines.push(section.content)
  }
  const combined = buildNameWithDate(section?.userName, section?.date)
  if (combined) {
    lines.push(combined)
  }
  return lines
}

const resetApprovalSummary = () => {
  approvalSummary.departmentReview.userName = ''
  approvalSummary.departmentReview.date = ''
  approvalSummary.departmentReview.content = ''

  approvalSummary.officeReview.userName = ''
  approvalSummary.officeReview.date = ''
  approvalSummary.officeReview.content = ''

  approvalSummary.deputyReview.userName = ''
  approvalSummary.deputyReview.date = ''
  approvalSummary.deputyReview.content = ''

  approvalSummary.signer.userName = ''
  approvalSummary.signer.date = ''
  approvalSummary.signer.content = ''

  approvalSummary.proofreader.userName = ''
  approvalSummary.proofreader.date = ''
  approvalSummary.proofreader.content = ''

  approvalSummary.sealDate = ''
}

const populateApprovalSummary = (records: any[]) => {
  resetApprovalSummary()

  if (!Array.isArray(records) || records.length === 0) {
    return
  }

  const needMajorLeader = Number(documentDetail.value?.issueNumberApproval || 0) === 1

  records.forEach((record: any) => {
    const stepName: string = (record?.stepName || record?.approverRole || '').trim()
    if (!stepName) return

    if (!record?.approvedAt) return
    if (isRejectedStatus(record?.status)) return

    const rawComment = extractApprovalComment(record)
    const entry = {
      userName: record?.approverName || '',
      date: record?.approvedAt || record?.createdAt || '',
      content: rawComment && rawComment !== '-' ? rawComment : '',
    }

    if (stepName.includes('科室负责人')) {
      approvalSummary.departmentReview.userName = entry.userName
      approvalSummary.departmentReview.date = entry.date
      approvalSummary.departmentReview.content = entry.content
      return
    }

    if (stepName.includes('办公室')) {
      approvalSummary.officeReview.userName = entry.userName
      approvalSummary.officeReview.date = entry.date
      approvalSummary.officeReview.content = entry.content
      return
    }

    if (stepName.includes('分管领导')) {
      if (needMajorLeader) {
        approvalSummary.deputyReview.userName = entry.userName
        approvalSummary.deputyReview.date = entry.date
        approvalSummary.deputyReview.content = entry.content
      } else {
        approvalSummary.signer.userName = entry.userName
        approvalSummary.signer.date = entry.date
        approvalSummary.signer.content = entry.content
      }
      return
    }

    if (stepName.includes('主要领导') || stepName.includes('签发')) {
      approvalSummary.signer.userName = entry.userName
      approvalSummary.signer.date = entry.date
      approvalSummary.signer.content = entry.content
      return
    }

    if (stepName.includes('校对') || stepName.includes('登记编号套红')) {
      approvalSummary.proofreader.userName = entry.userName
      approvalSummary.proofreader.date = entry.date
      approvalSummary.proofreader.content = entry.content
      return
    }

    if (stepName.includes('文件分发') || stepName.includes('分发')) {
      approvalSummary.sealDate = entry.date
    }
  })
}

watch(
  () => documentDetail.value?.issueNumberApproval,
  () => {
    if (flowRecords.value.length > 0) {
      populateApprovalSummary(flowRecords.value)
    }
  },
)

// 文件名称展示（去除时间戳前缀）
const showFileName = (filename: string) => {
  if (!filename) return '未知文件'
  // 找到第一个下划线的位置
  const firstUnderscore = filename.indexOf('_')
  if (firstUnderscore === -1) return filename

  // 从第一个下划线之后开始找第二个下划线
  const secondUnderscore = filename.indexOf('_', firstUnderscore + 1)
  if (secondUnderscore === -1) return filename

  // 截取第二个下划线之后的部分
  return filename.substring(secondUnderscore + 1)
}

// 判断文件是否可以预览
const canPreview = (fileName: string) => {
  if (!fileName) return false
  const ext = fileName.toLowerCase().split('.').pop()
  return ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'].includes(ext || '')
}

// 加载附件列表
const loadAttachments = async () => {
  if (!documentId.value) return

  try {
    console.log('[loadAttachments] 加载附件列表, documentId:', documentId.value)

    const response = await getDocumentAttachments(documentId.value)
    console.log('[loadAttachments] 原始响应:', response)

    if (response.code === 200 && response.data) {
      attachmentList.value = Array.isArray(response.data) ? response.data : []
      console.log('[loadAttachments] 附件列表加载成功:', attachmentList.value.length, '个附件')
    } else {
      console.warn('[loadAttachments] 响应失败:', response)
      attachmentList.value = []
    }
  } catch (error: any) {
    console.error('[loadAttachments] 加载附件列表失败:', error)
    attachmentList.value = []
  }
}

// Tab切换
const switchTab = (tab: 'detail' | 'flow' | 'attachments' | 'redHeader') => {
  activeTab.value = tab
  if (tab === 'flow') {
    loadFlowRecords()
  }
  if (tab === 'attachments' && attachmentList.value.length === 0) {
    loadAttachments()
  }
}

// 返回上一页
const goBack = () => {
  const pages = getCurrentPages()
  if (pages.length <= 1) {
    uni.reLaunch({
      url: '/pages/index/index',
    })
  } else {
    uni.navigateBack({
      delta: 1,
    })
  }
}

// 显示更多操作
const showMoreActions = () => {
  const actions = ['刷新']

  // 如果不是审批模式，添加其他操作
  if (!showApprovalActions.value) {
    actions.push('分享')
  }

  uni.showActionSheet({
    itemList: actions,
    success: (res) => {
      if (res.tapIndex === 0) {
        loadDocumentDetail()
      }
    },
  })
}

// 加载公文详情
const loadDocumentDetail = async () => {
  if (!documentId.value) {
    uni.showToast({
      title: '参数错误',
      icon: 'none',
    })
    return
  }

  try {
    loading.value = true
    console.log('[loadDocumentDetail] 加载公文详情, ID:', documentId.value)

    const response = await getDocumentDetail(documentId.value)

    if (response.code === 200 && response.data) {
      documentDetail.value = response.data
      console.log('[loadDocumentDetail] 公文详情加载成功:', documentDetail.value)
      await loadFlowRecords(true)
    } else {
      throw new Error(response.message || '获取公文详情失败')
    }
  } catch (error: any) {
    console.error('[loadDocumentDetail] 加载公文详情失败:', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none',
    })
  } finally {
    loading.value = false
  }
}

// 加载流程记录
const loadFlowRecords = async (force = false) => {
  if (!documentId.value) return

  if (flowRecordsLoaded.value && !force) {
    return
  }

  try {
    console.log('[loadFlowRecords] 加载流程记录, ID:', documentId.value)

    const response = await getApprovalFlowRecords(documentId.value)
    console.log('[loadFlowRecords] 原始响应:', response)

    // uni-app 标准响应结构：{ code: 200, message: "...", data: {...} }
    if (response.code === 200 && response.data) {
      // 尝试多种可能的数据结构
      const records = response.data.records || response.data || []

      console.log('[loadFlowRecords] 提取的records:', records)

      // 按时间倒序排列
      if (Array.isArray(records) && records.length > 0) {
        flowRecords.value = [...records].reverse()
        console.log('[loadFlowRecords] 流程记录加载成功:', flowRecords.value.length, '条')
        console.log('[loadFlowRecords] 第一条记录:', flowRecords.value[0])
      } else {
        console.warn('[loadFlowRecords] records不是数组或为空:', records)
        flowRecords.value = []
      }
    } else {
      console.warn('[loadFlowRecords] 响应失败:', response)
      flowRecords.value = []
    }

    populateApprovalSummary(flowRecords.value)
    flowRecordsLoaded.value = true

    // 同时加载内部分发查看记录
    await loadInternalReceiveRecords()
  } catch (error: any) {
    console.error('[loadFlowRecords] 加载流程记录失败:', error)
    flowRecords.value = []
    resetApprovalSummary()
  }
}

// 加载内部分发查看记录
const loadInternalReceiveRecords = async () => {
  if (!documentId.value) return

  try {
    console.log('[loadInternalReceiveRecords] 加载内部分发记录, ID:', documentId.value)

    const response = await getInternalDocumentDistributions(documentId.value)
    console.log('[loadInternalReceiveRecords] 原始响应:', response)

    if (response.code === 200 && response.data) {
      const records = response.data || []
      internalReceiveRecords.value = Array.isArray(records) ? records : []
      console.log(
        '[loadInternalReceiveRecords] 内部分发记录加载成功:',
        internalReceiveRecords.value.length,
        '条',
      )
    } else {
      console.warn('[loadInternalReceiveRecords] 响应失败:', response)
      internalReceiveRecords.value = []
    }
  } catch (error: any) {
    console.error('[loadInternalReceiveRecords] 加载失败:', error)
    // 不显示错误提示，因为这是可选功能
    internalReceiveRecords.value = []
  }
}

// 预览文件（使用系统应用打开）
const previewFile = (filePath: string) => {
  console.log('[previewFile] 预览文件:', filePath)

  // 构建完整URL
  const fileUrl = filePath.startsWith('http')
    ? filePath
    : `${import.meta.env.VITE_API_BASE_URL || ''}${filePath}`

  // 获取文件扩展名
  const fileExtension = filePath.split('.').pop()?.toLowerCase() || ''

  uni.showLoading({ title: '正在打开文档...' })

  // 1. 先下载文件到本地临时目录
  uni.downloadFile({
    url: fileUrl,
    success: (res) => {
      if (res.statusCode === 200) {
        // 2. 使用 uni.openDocument 调用系统应用打开
        uni.openDocument({
          filePath: res.tempFilePath,
          fileType: fileExtension, // 指定文件类型：doc, docx, xls, xlsx, ppt, pptx, pdf
          showMenu: true, // 显示右上角菜单（分享、转发等）
          success: () => {
            uni.hideLoading()
            console.log('[previewFile] 文档打开成功')
          },
          fail: (err) => {
            uni.hideLoading()
            console.error('[previewFile] 文档打开失败:', err)

            // 提示用户可能的原因
            let errorMsg = '无法打开文档'
            if (err.errMsg && err.errMsg.includes('no application')) {
              errorMsg = '手机未安装支持的应用，请下载 WPS 或 Office'
            }

            uni.showModal({
              title: '提示',
              content: errorMsg + '\n是否直接下载文件？',
              confirmText: '下载',
              cancelText: '取消',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  downloadFile(filePath)
                }
              },
            })
          },
        })
      } else {
        uni.hideLoading()
        uni.showToast({
          title: '文件下载失败',
          icon: 'none',
        })
      }
    },
    fail: (err) => {
      uni.hideLoading()
      console.error('[previewFile] 下载失败:', err)
      uni.showToast({
        title: '文件下载失败，请检查网络',
        icon: 'none',
      })
    },
  })
}

// 下载附件（复用 downloadFile 方法）
const downloadAttachmentFile = (attachment: AttachmentInfo) => {
  console.log('[downloadAttachmentFile] 下载附件:', attachment)

  // 使用 filePath 字段（HTTP URL）
  if (attachment.filePath) {
    downloadFile(attachment.filePath)
  } else {
    uni.showToast({
      title: '附件地址不可用',
      icon: 'none',
    })
  }
}

// 预览附件（复用 previewFile 方法）
const previewAttachmentFile = (attachment: AttachmentInfo) => {
  console.log('[previewAttachmentFile] 预览附件:', attachment)

  // 使用 filePath 字段（HTTP URL）
  if (attachment.filePath) {
    previewFile(attachment.filePath)
  } else {
    uni.showToast({
      title: '附件地址不可用',
      icon: 'none',
    })
  }
}

// 下载文件（保存到本地）- 旧版方法，保留用于正文下载
const downloadFile = (filePath: string) => {
  console.log('[downloadFile] 下载文件:', filePath)

  // 构建完整URL
  const fileUrl = filePath.startsWith('http')
    ? filePath
    : `${import.meta.env.VITE_API_BASE_URL || ''}${filePath}`

  // 获取文件名
  const fileName = getFileName(filePath)

  uni.showLoading({ title: '正在下载...' })

  uni.downloadFile({
    url: fileUrl,
    success: (res) => {
      if (res.statusCode === 200) {
        // 保存文件到本地
        uni.saveFile({
          tempFilePath: res.tempFilePath,
          success: (saveRes) => {
            uni.hideLoading()
            console.log('[downloadFile] 文件已保存到:', saveRes.savedFilePath)

            // 提示用户文件保存成功
            uni.showModal({
              title: '下载成功',
              content: `文件已保存\n${fileName}\n是否立即打开？`,
              confirmText: '打开',
              cancelText: '稍后',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  // 用户选择打开，调用预览
                  uni.openDocument({
                    filePath: saveRes.savedFilePath,
                    showMenu: true,
                    fail: () => {
                      uni.showToast({
                        title: '无法打开文件',
                        icon: 'none',
                      })
                    },
                  })
                } else {
                  // 只是提示位置
                  uni.showToast({
                    title: '已保存到文件管理器',
                    icon: 'success',
                    duration: 2000,
                  })
                }
              },
            })
          },
          fail: (saveErr) => {
            uni.hideLoading()
            console.error('[downloadFile] 保存失败:', saveErr)
            uni.showToast({
              title: '文件保存失败',
              icon: 'none',
            })
          },
        })
      } else {
        uni.hideLoading()
        uni.showToast({
          title: '下载失败',
          icon: 'none',
        })
      }
    },
    fail: (err) => {
      uni.hideLoading()
      console.error('[downloadFile] 下载失败:', err)
      uni.showToast({
        title: '下载失败，请检查网络',
        icon: 'none',
      })
    },
  })
}

// 下载红头文件
const downloadRedHeader = () => {
  const filePath = documentDetail.value.redHeaderFilePdf || documentDetail.value.redHeaderFilePath
  if (filePath) {
    downloadFile(filePath)
  }
}

// 预览红头文件
const previewRedHeader = () => {
  const filePath = documentDetail.value.redHeaderFilePdf || documentDetail.value.redHeaderFilePath
  if (filePath) {
    previewFile(filePath)
  }
}

// 预览图片
const previewImage = (url: string) => {
  if (!url) return

  // 使用自定义预览，确保有白底
  previewImageUrl.value = url
  showImageModal.value = true
}

// 处理同意
const handleApprove = async () => {
  const stepName = documentDetail.value.currentStepName || ''
  console.log('[handleApprove] 当前步骤名称:', documentDetail.value)
  console.log('[handleApprove] 当前步骤名称:', stepName)
  // 判断是否是拟稿步骤
  if (stepName.includes('拟稿')) {
    // 拟稿步骤需要选择审批人员
    try {
      uni.showLoading({ title: '加载审批人员...' })

      // 加载可选审批人员
      await loadAvailableApprovers(documentDetail.value.id, documentDetail.value.currentStep || 1)

      uni.hideLoading()

      // 保存下一步骤名称
      nextStepName.value = documentDetail.value.nextStepName || '审批'

      // 重置表单
      approvalForm.value.action = 'approve'
      approvalForm.value.opinion = '-'
      selectedApprovers.value = []

      // 如果只有一个审批人员，自动选中
      if (availableApprovers.value.length === 1) {
        selectedApprovers.value = [availableApprovers.value[0].id]
      }

      // 显示选择审批人员弹窗
      showApproverSelectModal.value = true
    } catch (error) {
      uni.hideLoading()
      console.error('[handleApprove] 加载审批人员失败:', error)
      uni.showToast({
        title: '加载审批人员失败',
        icon: 'none',
      })
    }
    return
  }

  // 其他步骤：直接审批弹窗
  approvalForm.value.action = 'approve'
  // 如果有签名，意见为空，否则默认为“同意。”
  approvalForm.value.opinion = signaturePath.value ? '' : '同意。'
  showApprovalModal.value = true
}

// 处理拒绝
const handleReject = () => {
  approvalForm.value.action = 'reject'
  approvalForm.value.opinion = ''

  // 如果有签名，清空文字意见
  if (signaturePath.value) {
    approvalForm.value.opinion = ''
  }

  showApprovalModal.value = true
}

// 选择审批操作
const selectAction = (action: 'approve' | 'reject') => {
  approvalForm.value.action = action
  // 无论同意还是拒绝，如果有签名，意见都可为空；无签名时，同意默认为"同意。"，拒绝默认为空
  if (signaturePath.value) {
    approvalForm.value.opinion = ''
  } else {
    if (action === 'approve') {
      approvalForm.value.opinion = '同意。'
    } else {
      approvalForm.value.opinion = ''
    }
  }
}

// 关闭审批弹窗
const closeApprovalModal = () => {
  showApprovalModal.value = false
  approvalForm.value.action = ''
  approvalForm.value.opinion = ''
}

// 关闭选择审批人员弹窗
const closeApproverSelectModal = () => {
  showApproverSelectModal.value = false
  approvalForm.value.opinion = ''
  selectedApprovers.value = []
  availableApprovers.value = []
  nextStepName.value = ''
}

// 提交审批（带审批人员）
const submitApprovalWithApprovers = async () => {
  if (!canSubmitWithApprovers.value) {
    uni.showToast({
      title: '请选择审批人员并输入意见',
      icon: 'none',
    })
    return
  }

  if (isSubmitting.value) return // 防止重复提交
  isSubmitting.value = true

  try {
    uni.showLoading({ title: '正在提交...', mask: true })

    // 构建审批人列表
    const approvers = selectedApprovers.value.map((approverId) => {
      const approver = availableApprovers.value.find((a) => a.id === approverId)
      return {
        approverId: approverId,
        approverName: approver?.name || '未知',
        deptName: approver?.deptName || '未知部门',
      }
    })

    // 构建审批流程数据 - 所有审批人在同一个步骤中
    const approvalFlow = [
      {
        stepOrder: 1,
        stepName: '审批',
        approverRole: 'approver',
        approvers: approvers,
        approvalType: 'multiple',
        timeoutHours: 24,
        isRequired: 1,
        status: 'pending',
      },
    ]

    // 构建提交数据
    const submitData: any = {
      documentId: documentDetail.value.id,
      action: 'approve',
      opinion: approvalForm.value.opinion.trim() || '-', // 如果有签名且意见为空，传 '-'
      approvers: approvers,
      signature: signaturePath.value,
      flowSteps: approvalFlow.map((approver: any, index) => ({
        stepOrder: index + 1,
        stepName: `第${index + 1}步审批`,
        approverRole: 'approver',
        approverId: approver.approverId,
        approverName: approver.approverName,
        deptName: approver.deptName,
        approvalType: 'single',
        timeoutHours: 24,
        isRequired: 1,
        status: 'pending',
      })),
    }

    const response = await submitDocumentWithApprovers(documentDetail.value.id, submitData)

    // 响应拦截器已经处理过，直接判断 response.code
    if (response.code === 200 || response.result === 'success') {
      uni.hideLoading()
      uni.showToast({
        title: '提交成功',
        icon: 'success',
      })

      // 关闭弹窗
      closeApproverSelectModal()

      // 延迟返回，让 onShow 钩子刷新列表数据
      setTimeout(() => {
        // 智能返回：优先navigateBack，失败则跳转到对应的列表页
        uni.navigateBack({
          success: () => {
            console.log('[submitApprovalWithApprovers] 成功返回上一页，onShow将自动刷新数据')
          },
          fail: () => {
            // navigateBack失败时，跳转到待审批列表
            console.log('[submitApprovalWithApprovers] navigateBack失败，跳转到待审批列表')
            uni.redirectTo({
              url: '/pages/document/send/index?tab=todo',
              fail: () => {
                console.error('[submitApprovalWithApprovers] 跳转列表页也失败，返回首页')
                uni.reLaunch({
                  url: '/pages/index/index',
                })
              },
            })
          },
        })
      }, 1500)
    } else {
      isSubmitting.value = false // 提交失败，允许重试
      uni.hideLoading()
      uni.showToast({
        title: response.message || '提交失败',
        icon: 'none',
      })
    }
  } catch (error) {
    isSubmitting.value = false // 提交异常，允许重试
    uni.hideLoading()
    console.error('[submitApprovalWithApprovers] 提交失败:', error)
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none',
    })
  }
}

// 提交审批（新版本）
const submitApproval = async () => {
  if (!canSubmit.value) {
    uni.showToast({
      title: '请完善审批信息',
      icon: 'none',
    })
    return
  }

  if (isSubmitting.value) return // 防止重复提交
  isSubmitting.value = true

  try {
    uni.showLoading({ title: '正在提交...', mask: true })

    // 构建审批数据
    const approvalData = {
      documentId: documentDetail.value.id,
      stepOrder: documentDetail.value.currentStep || 1,
      approverId: getCurrentUserId() || 0,
      action: approvalForm.value.action,
      approvalResult: approvalForm.value.action === 'approve' ? 'approved' : 'rejected',
      opinion: approvalForm.value.opinion.trim() || '-', // 如果有签名且意见为空，传 '-'
      approvalComment: approvalForm.value.opinion.trim() || '-',
      signature: signaturePath.value,
      approvalAttachments: '',
    }

    let response: any = null

    // 特殊处理：分管领导批示且不需要主要领导审批时，直接跳转到套红
    if (
      (documentDetail.value.currentStepName === '科室负责人审批' ||
        documentDetail.value.currentStepName === '分管领导批示') &&
      documentDetail.value.issueNumberApproval === 0 &&
      approvalForm.value.action === 'approve'
    ) {
      // 直接跳转到套红步骤
      response = await jumpAddRedStamp(approvalData.documentId, approvalData)
    } else {
      response = await submitDocumentApproval(approvalData.documentId, approvalData)
    }

    console.log('[submitApproval] 审批响应:', response)
    console.log('[submitApproval] 响应结构:', {
      code: response.code,
      result: response.result,
      data: response.data,
      message: response.message,
    })

    // 响应拦截器已经处理过，直接判断 response.code
    if (response.code === 200 || response.result === 'success') {
      uni.hideLoading()
      uni.showToast({
        title: approvalForm.value.action === 'approve' ? '审批成功' : '已拒绝',
        icon: 'success',
      })

      // 关闭弹窗
      closeApprovalModal()

      // 延迟返回，让 onShow 钩子刷新列表数据
      setTimeout(() => {
        // 智能返回：优先navigateBack，失败则跳转到对应的列表页
        uni.navigateBack({
          success: () => {
            console.log('[submitApproval] 成功返回上一页，onShow将自动刷新数据')
          },
          fail: () => {
            // navigateBack失败时，根据source跳转到对应的列表页
            console.log('[submitApproval] navigateBack失败，跳转到列表页')
            const tabMap: Record<string, string> = {
              todo: 'todo',
              approval: 'todo',
              redHeader: 'redHeader',
              seal: 'seal',
              distribute: 'distribute',
            }
            const tab = tabMap[source.value] || 'my'
            uni.redirectTo({
              url: `/pages/document/send/index?tab=${tab}`,
              fail: () => {
                console.error('[submitApproval] 跳转列表页也失败，返回首页')
                uni.reLaunch({
                  url: '/pages/index/index',
                })
              },
            })
          },
        })
      }, 1500)
    } else {
      isSubmitting.value = false // 提交失败，允许重试
      uni.hideLoading()
      uni.showToast({
        title: response.message || '审批失败',
        icon: 'none',
      })
    }
  } catch (error) {
    isSubmitting.value = false // 提交异常，允许重试
    uni.hideLoading()
    console.error('[submitApproval] 审批失败:', error)
    uni.showToast({
      title: '审批失败，请重试',
      icon: 'none',
    })
  }
}

// 处理套红操作（参考网页端实现）
const handleRedHeaderAction = async () => {
  try {
    const result = await uni.showModal({
      title: '套红确认',
      content: `确定要对《${documentDetail.value.title}》进行套红操作吗？\n\n套红成功后将自动提交到盖章流程`,
    })

    if (result.confirm) {
      uni.showLoading({ title: '套红中...' })

      // 生成红头文件保存路径
      const redHeaderFilePath =
        documentDetail.value.redHeaderFilePath ||
        `/uploads/red-header/${documentDetail.value.id}-${Date.now()}.docx`
      // 获取业务类别参数
      const bizCategory = documentDetail.value.bizCategory || ''

      console.log('[handleRedHeaderAction] 套红参数:', {
        id: documentDetail.value.id,
        redHeaderFilePath,
        bizCategory,
      })

      // 调用后端套红接口
      const response = await applyRedHeader(documentDetail.value.id, redHeaderFilePath, bizCategory)

      uni.hideLoading()

      if (response.code === 200) {
        uni.showToast({
          title: '套红成功并自动提交到盖章流程',
          icon: 'success',
          duration: 1500,
        })

        // 延迟返回列表，列表页会自动刷新数据
        setTimeout(() => {
          // 智能返回：优先navigateBack，失败则跳转到套红列表
          uni.navigateBack({
            success: () => {
              console.log('[handleRedHeaderAction] 成功返回上一页')
            },
            fail: () => {
              console.log('[handleRedHeaderAction] navigateBack失败，跳转到套红列表')
              uni.redirectTo({
                url: '/pages/document/send/index?tab=redHeader',
                fail: () => {
                  console.error('[handleRedHeaderAction] 跳转列表页也失败，返回首页')
                  uni.reLaunch({
                    url: '/pages/index/index',
                  })
                },
              })
            },
          })
        }, 1500)
      } else {
        throw new Error(response.message || '套红失败')
      }
    }
  } catch (error: any) {
    uni.hideLoading()
    console.error('[handleRedHeaderAction] 套红失败:', error)
    uni.showToast({
      title: error.message || '套红失败',
      icon: 'none',
    })
  }
}

// 处理签章操作
const handleSealAction = () => {
  console.log('[handleSealAction] 打开印章选择器')
  selectedSeal.value = null
  sealSelectorVisible.value = true
}

// 确认选择印章并执行签章
const handleSealConfirm = async (seal: SealInfo) => {
  console.log('[handleSealConfirm] 选择的印章:', seal)
  selectedSeal.value = seal

  try {
    uni.showLoading({ title: '签章中...' })

    const opinion = '已盖章'

    console.log('[handleSealConfirm] 签章参数:', {
      id: documentDetail.value.id,
      sealId: seal.id,
      sealName: seal.sealName,
      opinion,
    })

    const response = await applySeal(documentDetail.value.id, seal.id, opinion)

    uni.hideLoading()

    if (response.code === 200) {
      uni.showToast({
        title: '签章成功',
        icon: 'success',
        duration: 1500,
      })

      // 延迟返回列表，列表页会自动刷新数据
      setTimeout(() => {
        // 智能返回：优先navigateBack，失败则跳转到签章列表
        uni.navigateBack({
          success: () => {
            console.log('[handleSealConfirm] 成功返回上一页')
          },
          fail: () => {
            console.log('[handleSealConfirm] navigateBack失败，跳转到签章列表')
            uni.redirectTo({
              url: '/pages/document/send/index?tab=seal',
              fail: () => {
                console.error('[handleSealConfirm] 跳转列表页也失败，返回首页')
                uni.reLaunch({
                  url: '/pages/index/index',
                })
              },
            })
          },
        })
      }, 1500)
    } else {
      throw new Error(response.message || '签章失败')
    }
  } catch (error: any) {
    uni.hideLoading()
    console.error('[handleSealConfirm] 签章失败:', error)
    uni.showToast({
      title: error.message || '签章失败',
      icon: 'none',
    })
  }
}

// 处理分发操作
const handleDistributeAction = () => {
  console.log('[handleDistributeAction] 打开分发选择器')
  distributeSelectorVisible.value = true
}

// 确认分发
const handleDistributeConfirm = async (data: any) => {
  console.log('[handleDistributeConfirm] 分发数据:', data)

  try {
    uni.showLoading({ title: '分发中...' })

    // 分别处理外部和内部分发
    let externalSuccess = false
    let internalSuccess = false

    // 外部单位分发
    if (data.enableExternal && data.selectedCompanies.length > 0) {
      const externalPayload = {
        documentId: documentDetail.value.id,
        documentTitle: documentDetail.value.title || '',
        distributeType: 'external' as const,
        targetCompanyIds: data.selectedCompanies,
      }

      console.log('[handleDistributeConfirm] 外部单位分发:', externalPayload)
      const resp = await distributeDocument(externalPayload)

      if (resp.code === 200) {
        externalSuccess = true
      } else {
        throw new Error(resp.message || '外部单位分发失败')
      }
    } else {
      externalSuccess = true // 未启用视为成功
    }

    // 内部部门分发
    if (data.enableInternal && data.selectedDepartments.length > 0) {
      const internalPayload = {
        documentId: documentDetail.value.id,
        documentTitle: documentDetail.value.title || '',
        distributeType: 'internal' as const,
        targetDepartments: data.selectedDepartments,
      }

      console.log('[handleDistributeConfirm] 内部部门分发:', internalPayload)
      const resp = await distributeDocument(internalPayload)

      if (resp.code === 200) {
        internalSuccess = true
      } else {
        throw new Error(resp.message || '内部部门分发失败')
      }
    } else {
      internalSuccess = true // 未启用视为成功
    }

    uni.hideLoading()

    // 显示结果
    if (externalSuccess && internalSuccess) {
      uni.showToast({
        title: '分发成功',
        icon: 'success',
        duration: 1500,
      })

      // 延迟返回列表，列表页会自动刷新数据
      setTimeout(() => {
        // 智能返回：优先navigateBack，失败则跳转到分发列表
        uni.navigateBack({
          success: () => {
            console.log('[handleDistributeConfirm] 成功返回上一页')
          },
          fail: () => {
            console.log('[handleDistributeConfirm] navigateBack失败，跳转到分发列表')
            uni.redirectTo({
              url: '/pages/document/send/index?tab=distribute',
              fail: () => {
                console.error('[handleDistributeConfirm] 跳转列表页也失败，返回首页')
                uni.reLaunch({
                  url: '/pages/index/index',
                })
              },
            })
          },
        })
      }, 1500)
    } else {
      throw new Error('部分分发失败')
    }
  } catch (error: any) {
    uni.hideLoading()
    console.error('[handleDistributeConfirm] 分发失败:', error)
    uni.showToast({
      title: error.message || '分发失败',
      icon: 'none',
    })
  }
}

// 提交审批（旧版本兼容）
const submitApprovalOld = async (action: string, opinion: string) => {
  try {
    uni.showLoading({ title: '提交中...' })

    const approvalData = {
      stepOrder: documentDetail.value.currentStep || 1,
      action: action,
      approvalResult: action === 'approve' ? 'approved' : 'rejected',
      opinion: opinion,
      approvalComment: opinion,
    }
    const response = await submitDocumentApproval(documentDetail.value.id, approvalData)

    uni.hideLoading()

    if (response.code === 200 || response.result === 'success') {
      uni.showToast({
        title: action === 'approve' ? '审批成功' : '已拒绝',
        icon: 'success',
      })

      // 延迟返回列表页，onShow 会自动刷新数据
      setTimeout(() => {
        uni.navigateBack({
          delta: 1,
          success: () => {
            console.log('[submitApprovalOld] 成功返回到审批列表页，onShow将自动刷新数据')
          },
        })
      }, 1500)
    } else {
      throw new Error(response.message || '审批失败')
    }
  } catch (error: any) {
    uni.hideLoading()
    console.error('[submitApproval] 提交审批失败:', error)
    uni.showToast({
      title: error.message || '审批失败',
      icon: 'none',
    })
  }
}

// 页面加载 - 使用 onLoad 接收页面参数
onLoad(async (options: any) => {
  console.log('[onLoad] 接收到的页面参数:', options)
  // 确保用户信息存在
  await UserManager.ensureUserInfo()

  // 解析 documentId
  if (options.id) {
    const parsedId = Number(options.id)
    if (!isNaN(parsedId) && parsedId > 0) {
      documentId.value = parsedId
    }
  }

  // 解析 source
  source.value = options.source || 'view'

  console.log('[onLoad] 解析后的参数:', {
    documentId: documentId.value,
    source: source.value,
    currentStepName: options.currentStepName,
    currentStep: options.currentStep,
    nextStepName: options.nextStepName,
    issueNumberApproval: options.issueNumberApproval,
    isValid: documentId.value > 0,
  })

  if (documentId.value > 0) {
    await loadDocumentDetail()

    // 加载附件列表
    await loadAttachments()

    // 如果URL参数中包含步骤信息，用它们补充或覆盖documentDetail
    if (options.currentStepName) {
      documentDetail.value.currentStepName = decodeURIComponent(options.currentStepName)
    }
    if (options.currentStep) {
      documentDetail.value.currentStep = Number(options.currentStep)
    }
    if (options.nextStepName) {
      documentDetail.value.nextStepName = decodeURIComponent(options.nextStepName)
    }
    if (options.issueNumberApproval !== undefined) {
      documentDetail.value.issueNumberApproval = Number(options.issueNumberApproval)
    }

    console.log('[onLoad] 补充后的documentDetail步骤信息:', {
      currentStepName: documentDetail.value.currentStepName,
      currentStep: documentDetail.value.currentStep,
      nextStepName: documentDetail.value.nextStepName,
      issueNumberApproval: documentDetail.value.issueNumberApproval,
    })
  } else {
    console.error('[onLoad] 无效的公文ID:', options.id)
    uni.showToast({
      title: '缺少公文ID参数',
      icon: 'none',
    })
  }
})
</script>

<style lang="scss" scoped>
.detail-page {
  height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  /* 顶部导航 */
  .nav-header {
    background: #1678ff;
    padding: 46px 32rpx 20rpx 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: white;
    flex-shrink: 0;

    .nav-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .back-icon {
        font-size: 40rpx;
        font-weight: bold;
      }
    }

    .nav-center {
      flex: 1;
      text-align: center;

      .nav-title {
        font-size: 36rpx;
        font-weight: bold;
      }
    }

    .nav-right {
      min-width: 22px;
      .save-btn {
        font-size: 28rpx;
        padding: 12rpx 24rpx;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 12rpx;
      }
    }
  }

  /* 加载状态 */
  .loading-container {
    text-align: center;
    padding: 120rpx 0;

    .loading-text {
      font-size: 28rpx;
      color: #999;
    }
  }

  /* 固定头部区域 */
  .fixed-header {
    flex-shrink: 0;
    padding: 24rpx;
    background: #f5f7fa;
  }

  /* 可滚动内容区域 */
  .scroll-content-wrapper {
    flex: 1;
    overflow-y: auto;
    padding: 0 24rpx;
    padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
  }

  /* 公文标题 */
  .title-section {
    background: white;
    border-radius: 16rpx;
    padding: 8rpx 24rpx;
    margin-bottom: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
    display: flex;
    justify-content: space-between;
    align-items: center;

    .document-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      line-height: 1.5;
      display: block;
    }

    .category-badge {
      padding: 6rpx 16rpx;
      border-radius: 8rpx;
      font-size: 24rpx;
      background: #ecf5ff;
      border: 1px solid #d9ecff;
      flex-shrink: 0;

      .badge-text {
        color: #1890ff;
        font-size: 24rpx;
      }
    }

    .category-badge-party {
      padding: 6rpx 16rpx;
      border-radius: 8rpx;
      font-size: 24rpx;
      background: #f0f9eb;
      border: 1px solid #e1f3d8;
      flex-shrink: 0;

      .badge-text {
        color: #67c23a;
        font-size: 24rpx;
      }
    }
  }

  /* 基本信息卡片 */
  .info-card {
    background: white;
    border-radius: 16rpx;
    padding: 0 24rpx;
    margin-bottom: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);

    .info-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      &.highlight {
        background: #f8f9fa;
        margin: 0 -24rpx;
        padding: 20rpx 24rpx;
        border-bottom: none;
      }

      .label {
        font-size: 26rpx;
        color: #666;
        flex-shrink: 0;
        margin-right: 20rpx;
      }

      .value {
        font-size: 28rpx;
        color: #333;
        text-align: right;
        flex: 1;

        &.current-step {
          color: #f56c6c;
          font-weight: bold;
        }

        &.next-step {
          color: #409eff;
          font-weight: 500;
        }
      }

      .urgency-badge {
        padding: 6rpx 16rpx;
        border-radius: 8rpx;
        font-size: 22rpx;

        &.urgent {
          background: #ffebee;
          .badge-text {
            color: #c62828;
          }
        }

        &.high {
          background: #fff3e0;
          .badge-text {
            color: #f57c00;
          }
        }

        &.normal {
          background: #e8f5e9;
          .badge-text {
            color: #2e7d32;
          }
        }
      }
    }
  }

  /* Tab切换 */
  .tab-section {
    display: flex;
    background: white;
    border-radius: 16rpx;
    padding: 8rpx 8rpx 0 8rpx;
    margin-bottom: 0;
    margin-top: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
    overflow-x: auto;
    white-space: nowrap;

    .tab-item {
      flex-shrink: 0;
      min-width: 150rpx;
      text-align: center;
      padding: 20rpx 24rpx;
      border-radius: 12rpx 12rpx 0 0;
      transition: all 0.3s ease;
      margin-right: 8rpx;
      position: relative;

      &:last-child {
        margin-right: 0;
      }

      &.active {
        background: #1890ff;
        box-shadow: 0 -4rpx 12rpx rgba(102, 126, 234, 0.2);

        .tab-text {
          color: white;
        }
      }

      .tab-text {
        font-size: 28rpx;
        font-weight: 500;
        color: #666;
      }
    }
  }

  /* 内容区域 */
  .content-section {
    background: white;
    border-radius: 16rpx;
    padding: 24rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);

    .detail-content {
      .section-block {
        margin-bottom: 32rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .block-header {
          display: flex;
          align-items: center;
          margin-bottom: 16rpx;
          padding-bottom: 12rpx;
          border-bottom: 2rpx solid #f0f0f0;

          .block-title {
            font-size: 30rpx;
            font-weight: bold;
            color: #333;
            position: relative;
            padding-left: 16rpx;

            &::before {
              content: '';
              position: absolute;
              left: 0;
              top: 50%;
              transform: translateY(-50%);
              width: 6rpx;
              height: 24rpx;
              background: linear-gradient(to bottom, #4facfe, #00f2fe);
              border-radius: 3rpx;
            }
          }

          .attachment-count {
            font-size: 24rpx;
            color: #999;
            margin-left: 8rpx;
          }
        }

        .word-content {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: space-between;

          .file-actions-row {
            display: flex;
            flex-direction: row;
            align-items: center;
            gap: 10rpx;

            .action-btn {
              display: flex;
              flex-direction: row;
              align-items: center;
              justify-content: center;
              gap: 10rpx;
              padding: 10rpx 16rpx;
              border-radius: 10rpx;
              background-color: #1890ff;
              color: #ffffff;
              font-size: 24rpx;
            }
          }
        }

        .block-content {
          .detail-row {
            display: flex;
            margin-bottom: 16rpx;
            line-height: 1.6;

            &:last-child {
              margin-bottom: 0;
            }

            &.multi-line-row {
              align-items: flex-start;
            }

            .row-label {
              font-size: 26rpx;
              color: #666;
              flex-shrink: 0;
              min-width: 140rpx;
            }

            .row-value {
              font-size: 26rpx;
              color: #333;
              flex: 1;

              &.link-text {
                color: #667eea;
                text-decoration: underline;
              }

              &.column {
                display: flex;
                flex-direction: column;
                align-items: flex-start;
                gap: 8rpx;
                text-align: left;
              }

              .row-line {
                font-size: 26rpx;
                color: #333;
                text-align: left;
              }
            }
          }

          .content-text {
            font-size: 28rpx;
            color: #333;
            line-height: 1.8;
            display: block;
          }

          .file-item {
            padding: 24rpx;
            background: #f8f9fa;
            border-radius: 12rpx;
            border: 1rpx solid #e5e7eb;
            margin-bottom: 16rpx;

            .file-info-row {
              display: flex;
              align-items: center;
              margin-bottom: 16rpx;

              .file-label {
                font-size: 26rpx;
                color: #666;
                flex-shrink: 0;
              }

              .file-name {
                font-size: 26rpx;
                color: #333;
                font-weight: 500;
                flex: 1;
                word-break: break-all;
              }
            }

            .file-actions-row {
              display: flex;
              gap: 16rpx;

              .action-btn {
                flex: 1;
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 8rpx;
                padding: 16rpx;
                border-radius: 8rpx;
                transition: all 0.3s ease;

                &.preview {
                  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);

                  .btn-icon,
                  .btn-text {
                    color: white;
                  }

                  &:active {
                    opacity: 0.8;
                  }
                }

                &.download {
                  background: white;
                  border: 2rpx solid #1890ff;

                  .btn-icon,
                  .btn-text {
                    color: #1890ff;
                  }

                  &:active {
                    background: #f0f5ff;
                  }
                }

                .btn-icon {
                  font-size: 28rpx;
                }

                .btn-text {
                  font-size: 26rpx;
                  font-weight: 500;
                }
              }
            }
          }

          .attachment-item {
            display: flex;
            align-items: center;
            padding: 20rpx;
            margin-bottom: 12rpx;
            background: #f8f9fa;
            border-radius: 12rpx;
            border: 1rpx solid #e5e7eb;

            &:last-child {
              margin-bottom: 0;
            }

            .file-icon {
              font-size: 32rpx;
              margin-right: 12rpx;
            }

            .file-name {
              flex: 1;
              font-size: 26rpx;
              color: #333;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .download-icon {
              font-size: 32rpx;
              color: #1890ff;
              margin-left: 12rpx;
            }
          }
        }
      }
    }

    /* 流程记录 */
    .flow-records {
      .record-item {
        display: flex;
        margin-bottom: 40rpx;

        &:last-child {
          margin-bottom: 0;

          .timeline-line {
            display: none;
          }
        }

        .record-timeline {
          position: relative;
          width: 48rpx;
          flex-shrink: 0;
          display: flex;
          flex-direction: column;
          align-items: center;

          .timeline-dot {
            width: 24rpx;
            height: 24rpx;
            border-radius: 50%;
            border: 4rpx solid #1890ff;
            background: white;
            z-index: 2;

            &.approved {
              border-color: #67c23a;
              background: #67c23a;
            }

            &.rejected {
              border-color: #f56c6c;
              background: #f56c6c;
            }

            &.pending {
              border-color: #e6a23c;
              background: white;
            }

            &.returned {
              border-color: #909399;
              background: #909399;
            }
          }

          .timeline-line {
            flex: 1;
            width: 2rpx;
            background: #e5e7eb;
            margin-top: 8rpx;
          }
        }

        .record-content {
          flex: 1;
          margin-left: 16rpx;
          padding-bottom: 8rpx;

          .record-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12rpx;

            .step-name {
              font-size: 28rpx;
              font-weight: bold;
              color: #333;
            }

            .status-badge {
              padding: 6rpx 16rpx;
              border-radius: 8rpx;
              font-size: 22rpx;

              &.approved {
                background: #e8f5e9;
                .status-text {
                  color: #2e7d32;
                }
              }

              &.rejected {
                background: #ffebee;
                .status-text {
                  color: #c62828;
                }
              }

              &.pending {
                background: #fff8e1;
                .status-text {
                  color: #f57f17;
                }
              }

              &.returned {
                background: #f5f5f5;
                .status-text {
                  color: #616161;
                }
              }
            }
          }

          .record-info {
            margin-bottom: 12rpx;

            .info-text {
              display: block;
              font-size: 24rpx;
              color: #666;
              line-height: 1.6;
            }
          }

          .record-opinion {
            background: #f8f9fa;
            padding: 16rpx;
            border-radius: 8rpx;
            margin-bottom: 12rpx;

            .opinion-label {
              font-size: 24rpx;
              color: #666;
              display: block;
              margin-bottom: 6rpx;
            }

            .signature-box {
              background-color: #fff;
              padding: 8rpx;
              border-radius: 8rpx;
              display: inline-block;
              border: 1rpx solid #eee;
            }

            .opinion-text {
              font-size: 26rpx;
              color: #333;
              line-height: 1.6;
              display: block;
              min-height: 36rpx; /* 确保即使为空也占位 */
            }
          }

          .record-time {
            .time-text {
              font-size: 22rpx;
              color: #999;
            }
          }
        }
      }
    }

    .empty-flow {
      text-align: center;
      padding: 80rpx 0;

      .empty-icon {
        font-size: 80rpx;
        display: block;
        margin-bottom: 24rpx;
      }

      .empty-text {
        font-size: 28rpx;
        color: #999;
      }
    }

    /* 分发记录分隔标识 */
    .distribution-divider {
      width: 100%;
      display: flex;
      align-items: center;
      margin: 48rpx 0 32rpx;

      .divider-line {
        flex: 1;
        height: 2rpx;
        background: linear-gradient(
          90deg,
          transparent 0%,
          #e5e7eb 20%,
          #e5e7eb 80%,
          transparent 100%
        );
      }

      .divider-label {
        display: flex;
        align-items: center;
        gap: 12rpx;
        padding: 12rpx 24rpx;
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        border: 2rpx solid #cbd5e1;
        border-radius: 32rpx;
        font-size: 26rpx;
        font-weight: 600;
        color: #475569;
        white-space: nowrap;
        box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);

        .divider-icon {
          font-size: 28rpx;
          color: #1890ff;
        }

        .divider-text {
          font-size: 26rpx;
        }

        .divider-badge {
          background: #1890ff;
          color: white;
          padding: 4rpx 12rpx;
          border-radius: 16rpx;
          font-size: 22rpx;
          min-width: 32rpx;
          text-align: center;
        }
      }
    }

    /* 附件列表 */
    .attachments-list {
      .attachment-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 24rpx;
        margin-bottom: 16rpx;
        background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
        border-radius: 12rpx;
        border: 1rpx solid #e5e7eb;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
        transition: all 0.3s ease;

        &:last-child {
          margin-bottom: 0;
        }

        &:active {
          transform: scale(0.98);
          box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.08);
        }

        .file-info {
          flex: 1;
          display: flex;
          align-items: center;
          margin-right: 16rpx;

          .file-icon {
            font-size: 40rpx;
            margin-right: 16rpx;
            flex-shrink: 0;
          }

          .file-details {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 8rpx;
            min-width: 0;

            .file-name {
              font-size: 28rpx;
              color: #333;
              font-weight: 500;
              word-break: break-all;
              line-height: 1.4;
            }

            .file-meta {
              display: flex;
              align-items: center;
              gap: 16rpx;
              flex-wrap: wrap;

              .file-size {
                font-size: 22rpx;
                color: #999;
                padding: 4rpx 12rpx;
                background: #f0f0f0;
                border-radius: 4rpx;
              }

              .file-uploader {
                font-size: 22rpx;
                color: #666;
              }
            }
          }
        }

        .file-actions {
          display: flex;
          gap: 24rpx;
          flex-shrink: 0;

          .action-icon {
            font-size: 36rpx;
            padding: 8rpx;
            transition: all 0.2s ease;

            &.download {
              color: #1890ff;

              &:active {
                transform: scale(1.2);
              }
            }

            &.preview {
              color: #67c23a;

              &:active {
                transform: scale(1.2);
              }
            }
          }
        }
      }
    }

    /* 空附件状态 */
    .empty-attachments {
      text-align: center;
      padding: 80rpx 0;

      .empty-icon {
        font-size: 80rpx;
        display: block;
        margin-bottom: 24rpx;
        opacity: 0.3;
      }

      .empty-text {
        font-size: 28rpx;
        color: #999;
      }
    }

    /* 红头文件 */
    .red-header-section {
      .preview-tip {
        text-align: center;
        padding: 32rpx 0 24rpx;
        border-bottom: 1rpx solid #f0f0f0;
        margin-bottom: 24rpx;

        .tip-icon {
          font-size: 60rpx;
          display: block;
          margin-bottom: 12rpx;
        }

        .tip-text {
          font-size: 30rpx;
          color: #333;
          font-weight: 500;
        }
      }

      .red-header-actions {
        display: flex;
        gap: 16rpx;

        .action-btn-red {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8rpx;
          padding: 24rpx;
          border-radius: 12rpx;
          transition: all 0.3s ease;

          &.preview {
            background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);

            .btn-icon,
            .btn-text {
              color: white;
            }

            &:active {
              opacity: 0.8;
            }
          }

          &.download {
            background: white;
            border: 2rpx solid #1890ff;

            .btn-icon,
            .btn-text {
              color: #1890ff;
            }

            &:active {
              background: #f0f5ff;
            }
          }

          .btn-icon {
            font-size: 32rpx;
          }

          .btn-text {
            font-size: 28rpx;
            font-weight: 500;
          }
        }
      }
    }
  }

  /* 错误状态 */
  .error-state {
    text-align: center;
    padding: 120rpx 60rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16rpx;

    .error-icon {
      font-size: 80rpx;
      display: block;
      margin-bottom: 12rpx;
    }

    .error-text {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 16rpx;
    }

    .error-btn {
      padding: 16rpx 48rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 12rpx;
      font-size: 26rpx;
    }
  }

  /* 底部操作栏 */
  .bottom-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: white;
    padding: 20rpx 32rpx;
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    display: flex;
    gap: 24rpx;
    box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.08);
    z-index: 99;
    border-top: 1rpx solid #f0f0f0;

    /* 单个按钮时占满整行 */
    &.single-action {
      .action-btn {
        flex: 1;
        height: 96rpx;
      }
    }

    .action-btn {
      flex: 1;
      height: 88rpx;
      border-radius: 16rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30rpx;
      font-weight: bold;
      transition: all 0.3s ease;

      &.reject {
        background: white;
        border: 2rpx solid #f56c6c;

        .btn-text {
          color: #f56c6c;
        }

        &:active {
          background: #ffebee;
        }
      }

      &.approve {
        background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
        box-shadow: 0 4rpx 12rpx rgba(103, 194, 58, 0.3);

        .btn-text {
          color: white;
        }

        &:active {
          opacity: 0.8;
        }
      }

      &.primary {
        background: #1890ff;
        box-shadow: 0 4rpx 12rpx rgba(58, 122, 194, 0.3);

        .btn-text {
          color: white;
        }

        &:active {
          opacity: 0.8;
        }
      }

      &.red-header {
        background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        box-shadow: 0 4rpx 12rpx rgba(250, 112, 154, 0.3);

        .btn-text {
          color: white;
          font-size: 32rpx;
        }

        &:active {
          opacity: 0.8;
        }
      }

      &.seal {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        box-shadow: 0 4rpx 12rpx rgba(240, 147, 251, 0.3);

        .btn-text {
          color: white;
          font-size: 32rpx;
        }

        &:active {
          opacity: 0.8;
        }
      }

      &.distribute {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);

        .btn-text {
          color: white;
          font-size: 32rpx;
        }

        &:active {
          opacity: 0.8;
        }
      }
    }
  }
}

/* 审批弹窗 */
.approval-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 40rpx;

  .modal-content {
    background: white;
    border-radius: 24rpx;
    width: 100%;
    max-width: 600rpx;
    max-height: 80vh;
    overflow: hidden;
    box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.3);

    .modal-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 32rpx 32rpx 24rpx;
      border-bottom: 1rpx solid #f0f0f0;

      .modal-title {
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
      }

      .close-btn {
        font-size: 40rpx;
        color: #999;
        padding: 8rpx;
      }
    }

    .modal-body {
      padding: 32rpx;

      .approval-actions {
        display: flex;
        gap: 16rpx;
        margin-bottom: 32rpx;

        .action-option {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 12rpx;
          padding: 24rpx;
          border: 2rpx solid #e5e7eb;
          border-radius: 12rpx;
          transition: all 0.3s ease;

          &.active {
            border-color: #1890ff;
            background: #1890ff;

            .option-icon,
            .option-text {
              color: white;
            }
          }

          .option-icon {
            font-size: 32rpx;
            color: #1890ff;
          }

          .option-text {
            font-size: 28rpx;
            font-weight: 500;
            color: #333;
          }
        }
      }

      .opinion-section {
        margin-bottom: 24rpx;

        .section-label {
          display: block;
          font-size: 28rpx;
          color: #666;
          margin-bottom: 16rpx;
        }

        .opinion-textarea {
          width: 100%;
          min-height: 120rpx;
          padding: 16rpx;
          border: 2rpx solid #e5e7eb;
          border-radius: 8rpx;
          font-size: 28rpx;
          line-height: 1.5;
          resize: none;

          &:focus {
            border-color: #667eea;
          }
        }

        .char-count {
          display: block;
          text-align: right;
          font-size: 24rpx;
          color: #999;
          margin-top: 8rpx;
        }
      }

      .step-info {
        padding: 16rpx;
        background: #f8f9fa;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        gap: 8rpx;

        .info-label {
          font-size: 26rpx;
          color: #666;
        }

        .info-value {
          font-size: 26rpx;
          color: #333;
          font-weight: 500;
        }
      }
    }

    .modal-footer {
      display: flex;
      gap: 16rpx;
      padding: 24rpx 32rpx 32rpx;

      .footer-btn {
        flex: 1;
        height: 80rpx;
        border-radius: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 30rpx;
        font-weight: 500;
        transition: all 0.3s ease;

        &.cancel {
          background: #f5f5f5;
          color: #666;

          &:active {
            background: #e5e5e5;
          }
        }

        &.confirm {
          background: #1890ff;
          color: white;

          &:active {
            opacity: 0.8;
          }

          &.disabled {
            background: #ccc;
            color: #999;
          }
        }
      }
    }
  }
}

/* 选择审批人员弹窗 */
.approver-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  padding: 20rpx;

  .modal-content-large {
    background: white;
    border-radius: 24rpx;
    width: 100%;
    max-height: 90vh;
    display: flex;
    flex-direction: column;
    box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
  }

  .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx 32rpx 24rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .modal-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }

    .close-btn {
      font-size: 40rpx;
      color: #999;
      padding: 8rpx;
    }
  }

  .modal-body-scroll {
    flex: 1;
    overflow-y: auto;
    padding: 32rpx;
  }

  /* 说明提示 */
  .approval-tip {
    background: #e3f2fd;
    border: 1rpx solid #90caf9;
    border-radius: 12rpx;
    padding: 24rpx;
    margin-bottom: 32rpx;
    display: flex;
    align-items: flex-start;
    gap: 16rpx;

    .tip-icon {
      font-size: 32rpx;
      color: #1976d2;
      line-height: 1;
    }

    .tip-content {
      flex: 1;

      .tip-text {
        font-size: 26rpx;
        color: #1565c0;
        line-height: 1.6;
        display: block;
        margin-bottom: 8rpx;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  /* 单人审批 */
  .single-approver {
    margin-bottom: 32rpx;

    .approver-card {
      background: #f1f8e9;
      border: 2rpx solid #aed581;
      border-radius: 16rpx;
      padding: 24rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .approver-info {
        flex: 1;

        .approver-name {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          display: block;
          margin-bottom: 8rpx;
        }

        .approver-dept {
          font-size: 26rpx;
          color: #689f38;
          display: block;
        }
      }

      .auto-tag {
        background: #689f38;
        padding: 8rpx 16rpx;
        border-radius: 8rpx;

        .tag-text {
          font-size: 24rpx;
          color: white;
        }
      }
    }
  }

  /* 多人审批 */
  .multi-approver {
    .approver-section,
    .selected-section {
      margin-bottom: 32rpx;

      .section-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 16rpx;
        display: block;
      }
    }

    /* 可选人员 */
    .approver-list {
      max-height: 400rpx;
      overflow-y: auto;
      border: 1rpx solid #e5e7eb;
      border-radius: 8rpx;
      padding: 4rpx;
      background: #fafafa;

      .approver-item {
        background: white;
        border-bottom: 1rpx solid #f0f0f0;
        padding: 12rpx 16rpx;
        margin-bottom: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        transition: all 0.3s;

        &:last-child {
          border-bottom: none;
        }

        &.selected {
          background: #eff6ff;
          border-bottom-color: #bfdbfe;

          .approver-name {
            color: #1e40af;
          }
        }

        &:active {
          background: #f5f5f5;
        }

        .approver-info {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .approver-name {
            font-size: 28rpx;
            font-weight: 600;
            color: #333;
            flex-shrink: 0;
          }

          .approver-dept {
            font-size: 24rpx;
            color: #999;
            text-align: right;
            flex-shrink: 0;
            margin-left: 16rpx;
          }
        }

        .check-icon {
          font-size: 36rpx;
          color: #4caf50;
          font-weight: bold;
          line-height: 1;
          flex-shrink: 0;
          margin-left: 12rpx;
        }
      }
    }

    /* 已选人员 */
    .selected-list {
      max-height: 250rpx;
      overflow-y: auto;
      border: 1rpx solid #93c5fd;
      border-radius: 8rpx;
      padding: 4rpx;
      background: #f0f9ff;

      .selected-item {
        background: white;
        border-bottom: 1rpx solid #bfdbfe;
        padding: 12rpx 16rpx;
        margin-bottom: 0;
        display: flex;
        align-items: center;
        gap: 12rpx;

        &:last-child {
          border-bottom: none;
        }

        .order-number {
          width: 40rpx;
          height: 40rpx;
          background: #3b82f6;
          color: white;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 22rpx;
          font-weight: bold;
          flex-shrink: 0;
        }

        .approver-info {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .approver-name {
            font-size: 28rpx;
            font-weight: 600;
            color: #1e40af;
            flex-shrink: 0;
          }

          .approver-dept {
            font-size: 24rpx;
            color: #64748b;
            text-align: right;
            flex-shrink: 0;
            margin-left: 16rpx;
          }
        }

        .remove-icon {
          width: 40rpx;
          height: 40rpx;
          background: #ef4444;
          color: white;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24rpx;
          line-height: 1;
          flex-shrink: 0;
        }
      }
    }
  }

  /* 意见输入区 */
  .opinion-section {
    margin-top: 24rpx;

    .section-label {
      display: block;
      font-size: 28rpx;
      color: #666;
      margin-bottom: 12rpx;
      font-weight: 500;
    }

    .opinion-textarea {
      width: 100%;
      min-height: 80rpx;
      max-height: 100rpx;
      padding: 16rpx;
      border: 2rpx solid #e5e7eb;
      border-radius: 8rpx;
      font-size: 26rpx;
      line-height: 1.5;
      resize: none;
      box-sizing: border-box;

      &:focus {
        border-color: #3b82f6;
      }
    }

    .char-count {
      display: block;
      text-align: right;
      font-size: 22rpx;
      color: #999;
      margin-top: 6rpx;
    }
  }

  .modal-footer {
    display: flex;
    gap: 16rpx;
    padding: 24rpx 32rpx 32rpx;
    border-top: 1rpx solid #f0f0f0;

    .footer-btn {
      flex: 1;
      height: 80rpx;
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30rpx;
      font-weight: 500;
      transition: all 0.3s ease;

      &.cancel {
        background: #f5f5f5;

        .btn-text {
          color: #666;
        }

        &:active {
          background: #e5e5e5;
        }
      }

      &.confirm {
        background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);

        .btn-text {
          color: white;
        }

        &:active {
          opacity: 0.8;
        }

        &.disabled {
          background: #ccc;

          .btn-text {
            color: #999;
          }
        }
      }
    }
  }
}

.signature-popup-container {
  width: 100vh;
  height: 100vw;
  background: white;
  display: flex;
  flex-direction: column;

  position: absolute;
  top: 50%;
  left: 50%;

  transform: translate(-50%, -50%) rotate(90deg);
  transform-origin: center center;
  overflow: hidden;

  .popup-header {
    position: relative;
    z-index: 10;
    background: white;
    padding: 24rpx 32rpx 24rpx 44px;
    border-bottom: 1rpx solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-shrink: 0;

    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .signature-content {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: 1;

    transform: rotate(-90deg);
    transform-origin: center center;

    /* 旋转后需要重新计算尺寸：旋转后的宽度 = 原高度，旋转后的高度 = 原宽度 */
    width: 100vw;
    height: 100vh;
    top: 50%;
    left: 50%;
    margin-left: -50vw;
    margin-top: -50vh;

    background: #f5f5f5;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;

    :deep(l-signature) {
      width: 100% !important;
      height: 100% !important;
    }
  }

  .popup-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 10;
    background: white;
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #eee;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    gap: 24rpx;
    width: 100%;

    .btn {
      flex: 1;
      max-width: 300rpx;
      height: 88rpx;
      border-radius: 44rpx;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      gap: 12rpx;
      font-size: 28rpx;
      font-weight: 500;
      padding: 0 32rpx;

      &.reset {
        background: #f3f4f6;
        color: #666;
        border: 1rpx solid #e5e7eb;
      }

      &.confirm {
        background: #1a3582;
        color: white;
      }
    }
  }
}
</style>
